import os, sys
from PyPDF2 import PdfFileReader, PdfFileWriter

def main(a_file, a2):
    s = PdfFileReader(a_file)
    s2 = s.getNumPages()
    
    for i in a2:
        s4_queueNum = 1
        pdfFileWriter = PdfFileWriter()
        s3 = i.split(":")
        if len(s3)==1:
            pdfFileWriter.addPage(s.getPage(int(s3[0])))
            s4_queueNum +=1
            pdfFileWriter.write(open(os.path.basename(a_file)[:-4]+' %s.pdf' %s4_queueNum, 'wb'))
        elif len(s3)==2:
            if s3[0]=='':
                s5_start = 0
            else:
                s5_start = int(s3[0])
            if s3[1]=='':
                s6_end = s2
            else:
                s6_end = int(s3[1])
            for i in range(s5_start, s6_end):
                pdfFileWriter.addPage(s.getPage(i))
            s4_queueNum +=1
            pdfFileWriter.write(open(os.path.basename(a_file)[:-4]+' %s.pdf' %s4_queueNum, 'wb'))
        elif len(s3)==3:
            pdfFileWriter = PdfFileWriter()
            if s3[0]=='':
                s5_start = 0
            else:
                s5_start = int(s3[0])
                if s5_start<0:
                    s5_start = s2+s5_start
            if s3[1]=='':
                s7_max = s2
            else:
                s7_max = int(s3[1])
            if s3[2]=='':
                s6_end = s2
            else:
                s6_end = int(s3[2])
                if s6_end<0:
                    s6_end = s2+s6_end
            s8 =0
            for i in range(s5_start, s6_end):
                pdfFileWriter.addPage(s.getPage(i))
                s8 +=1
                if s8>=s7_max or i==s6_end-1:
                    s8 =0
                    s4_queueNum +=1
                    pdfFileWriter.write(open(os.path.basename(a_file)[:-4]+' %s.pdf' %s4_queueNum, 'wb'))
                    pdfFileWriter = PdfFileWriter()

if __name__ == "__main__":
    if not len(sys.argv) <3:
        main(sys.argv[1], sys.argv[2:])
    else:
        print("Split a pdf:")
        print("... [path] [start_index:max:end_index]")
